package own.stu.jobgib.playown.tools.arthas;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) throws InterruptedException {

        Test t = new Test();
        t.highCpu();
        TimeUnit.MINUTES.sleep(10);
        t.stop = true;
        System.out.println("done");
    }

    private volatile boolean stop = false;
    private volatile long count = 0l;

    //  thread -n 1 查看cpu占用率topn的 线程
    private void highCpu() {
        new Thread(() -> {
            while (!stop) {
                count();
            }
        }, "t-high-cpu").start();
    }

    private void count() {
        try {
            count++;
            if (count % 1000_000 == 0) {
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println("print times : " + count);
                watchEx();
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private void stop() {
        stop = true;
    }

    private Random random = new Random();

    /*
    watch own.stu.jobgib.playown.tools.arthas.Test watchEx '{params,returnObj,throwExp}'  -n 3 -e -x 3
    查看方法调用情况，
    -n执行次数，
    -x 指定输出结果的属性遍历深度，默认为 1，最大值是 4
    -e 在函数异常之后观察
     */
    private int watchEx() throws Exception {
        int val = random.nextInt(20);
        if (val < 3) {
            throw new NoSuchMethodException("0000");
        } else if (val < 6) {
            throw new ReflectiveOperationException("1111");
        } else if(val < 10){
            throw new RuntimeException("2222");
        }
        return val;
    }
}
